package main

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"
)

type Bt struct {
	panelAddress string
	apiSecret    string
}

func NewBT(address string, secret string) *Bt {
	return &Bt{
		panelAddress: address,
		apiSecret:    secret,
	}
}

// GetSystemTotal 获取系统基础统计
func (bt *Bt) GetSystemTotal() (entity SystemTotalEntity, err error) {
	_url := bt.panelAddress + "/system?action=GetSystemTotal"
	data := bt.getKeyData()

	result, err := bt.HttpPost(_url, data)
	if err != nil {
		return
	}

	err = json.Unmarshal(result, &entity)

	return
}

// GetLogs 获取面板日志
func (bt *Bt) GetLogs() (entity LogEntity, err error) {
	_url := bt.panelAddress + "/data?action=getData"
	data := bt.getKeyData()
	data["limit"] = "15"
	data["table"] = "logs"
	data["tojs"] = "test"

	result, err := bt.HttpPost(_url, data)
	if err != nil {
		return
	}

	err = json.Unmarshal(result, &entity)

	return
}

// 拼接基础参数
func (bt *Bt) getKeyData() map[string]string {
	now := time.Now().Unix()
	token := bt.md5(fmt.Sprintf("%d%s", now, bt.md5(bt.apiSecret)))
	data := make(map[string]string)
	data["request_token"] = token
	data["request_time"] = strconv.FormatInt(now, 10)

	return data
}

// md5编码
func (bt *Bt) md5(s string) string {
	b := []byte(s)
	h := md5.New()
	h.Write(b)
	return hex.EncodeToString(h.Sum(nil))
}

func (bt *Bt) HttpPost(_url string, data map[string]string) ([]byte, error) {
	// 需要formData的格式
	params := url.Values{}
	for k, v := range data {
		params.Add(k, v)
	}

	client := &http.Client{}
	req, err := http.NewRequest("POST", _url, strings.NewReader(params.Encode()))
	if err != nil {
		return nil, err
	}
	// 必须
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	return io.ReadAll(resp.Body)
}
